import os
from concurrent.futures import ThreadPoolExecutor
from urllib.parse import urlparse

import requests

headers = {
    'Cookie': 'SINAGLOBAL=7143220498324.07.1603882784557; SCF=Av7qHTI3mB66x8BJIvjp_Jha_15WNj9hbP6cdhirj4i5bh8FB-OxhVBmIWYmkohaGyByPmD1inqASQ6vOUZp19E.; XSRF-TOKEN=uvqlOBu6pmAePZY8AJhg6aq8; SUB=_2A25KDXQqDeRhGeFJ71IU9y7PyjWIHXVpY4nirDV8PUNbmtAGLWL3kW9Nf-c9Co5Koosi5bp1KkpagnLRPdX5vbvW; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9WhRhJAT2r6ndZ1LKSGoJBIJ5JpX5KzhUgL.FoMNSh5fS050eK.2dJLoIp7LxKML1KBLBKnLxKqL1hnLBoMNS0B7SKM7e024; ALF=02_1731236218; _s_tentry=passport.weibo.com; Apache=3220482734023.8105.1728644222050; ULV=1728644222084:21:1:1:3220482734023.8105.1728644222050:1724376492042; WBPSESS=Dt2hbAUaXfkVprjyrAZT_Ptfs34Jffp1UvIKXtPfje1xzyIR1U9dzANiHAKZy3pB12RNHDNHDJEWIEorBmbdPYYVHQfvzSM_2gCKvdLUrvndpBW7EJ2E34Rpqf7md4qI4w1OsUIYthxUN9gKu9vMwxFbqOPNK5edXGbk9NWKUmaygWVAhDAHg_qvOsTuVovf5J9pcBhSoISmoUtCWeCkSg=='
}
thumbnail_urls = []

download_directory = 'C:/Users/Administrator/Desktop/wb6'

# 确保下载目录存在
if not os.path.exists(download_directory):
    os.makedirs(download_directory)


def down(list):
    for item in list:
        pic_infos = item.get("pic_infos", {})
        for pic_info in pic_infos.values():
            bmiddle_url = pic_info.get("largest", {}).get("url")
            if bmiddle_url and not bmiddle_url.startswith("http://zzx"):
                thumbnail_urls.append(bmiddle_url)  # 假设你只需要第一个 url，退出循环
    print(len(thumbnail_urls))


def download_image(url):
    try:
        print(url)
        re = requests.get(url)
        if re.status_code == 200:
            parsed_url = urlparse(url)
            filename = os.path.basename(parsed_url.path)
            name = os.path.join(download_directory, filename)
            with open(name, 'wb') as file:
                file.write(re.content)
                print(f"图片已保存到: {name}")
        else:
            print(f"下载失败，URL: {url}")
    except requests.RequestException as e:
        # 处理请求异常（如连接错误、超时等）
        print(f"下载失败，URL: {url}，错误信息: {e}")

    except Exception as e:
        # 处理其他异常
        print(f"处理文件失败，URL: {url}，错误信息: {e}")


# 使用多线程下载
def download_images_in_parallel(urls, max_workers=5):
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        executor.map(download_image, urls)


def down1(urlPath):
    resp = requests.get(urlPath, headers=headers)
    list = resp.json().get("data", {}).get("list", [])
    since_id = ""
    if not list:
        return since_id
    else:
        since_id = resp.json().get("data", {}).get("since_id", "")
        down(list)
        return since_id


def main():
    # down()
   #7839741548
    uid = "2104580380"
    since_id = "1"
    page = 0
    while since_id:
        if since_id == "1":
            url = f"https://weibo.com/ajax/statuses/mymblog?uid={uid}&feature=0&page={page}"
        else:
            url = f"https://weibo.com/ajax/statuses/mymblog?uid={uid}&feature=0&page={page}&since_id={since_id}"
        print(url)
        since_id = down1(url)
        print(since_id)
        page += 1

    # 调用多线程下载函数，最大并发5个线程
    # download_images_in_parallel(thumbnail_urls, max_workers=5)


if __name__ == '__main__':
    main()
